package com.yanzhenjie.andserver.sample.controller;

import android.os.Handler;
import android.os.Looper;
import com.alibaba.fastjson.JSONObject;
import com.panlin.printer.PrintModule;
import com.yanzhenjie.andserver.annotation.*;
import com.yanzhenjie.andserver.sample.model.BaseResponse;
import com.yanzhenjie.andserver.sample.model.PrintBarcodeRequest;
import com.yanzhenjie.andserver.sample.model.PrintImageRequest;
import com.yanzhenjie.andserver.sample.model.PrintTextRequest;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

@RestController
@RequestMapping("/api/print")
public class PrintController {
    private final PrintModule printModule = new PrintModule();
    private final Handler handler = new Handler(Looper.getMainLooper());

    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @GetMapping("/init")
    public BaseResponse init() {
        try {
            handler.post(printModule::init);
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("初始化打印机失败: " + e.getMessage());
        }
    }

    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @GetMapping("/free")
    public BaseResponse free() {
        try {
            handler.post(printModule::free);
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("释放打印机资源失败: " + e.getMessage());
        }
    }

    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @GetMapping("/initPrint")
    public BaseResponse initPrint() {
        try {
            handler.post(printModule::initPrint);
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("清除打印缓存失败: " + e.getMessage());
        }
    }

    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @GetMapping("/feedToNext")
    public BaseResponse feedToNext() {
        try {
            handler.post(printModule::Feed_to_Next);
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("走纸失败: " + e.getMessage());
        }
    }

    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @GetMapping("/blackLabelOn")
    public BaseResponse blackLabelOn() {
        try {
            handler.post(printModule::Black_label_On);
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("开启黑标检测失败: " + e.getMessage());
        }
    }

    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @GetMapping("/blackLabelOff")
    public BaseResponse blackLabelOff() {
        try {
            handler.post(printModule::Black_label_Off);
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("关闭黑标检测失败: " + e.getMessage());
        }
    }

    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @PostMapping("/sendData")
    public BaseResponse sendData(@RequestBody PrintTextRequest request) {
        try {
            JSONObject options = new JSONObject();
            options.put("content", request.getContent());
            handler.post(() -> printModule.sendData(options));
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("发送数据失败: " + e.getMessage());
        }
    }


    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @PostMapping("/printText")
    public BaseResponse printText(@RequestBody PrintTextRequest request) {
        try {
            JSONObject options = new JSONObject();
            options.put("content", request.getContent());
            options.put("charsetName", request.getCharsetName());
            handler.post(() -> printModule.printText(options));
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("打印文本失败: " + e.getMessage());
        }
    }

    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @PostMapping("/printImage")
    public BaseResponse printImage(@RequestBody PrintImageRequest request) {
        try {
            JSONObject options = new JSONObject();
            options.put("content", request.getContent());
            options.put("width", request.getWidth());
            options.put("height", request.getHeight());
            options.put("interval", request.getInterval());
            handler.post(() -> printModule.printImage(options));
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("打印图片失败: " + e.getMessage());
        }
    }


    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @PostMapping("/print")
    public BaseResponse print(@RequestBody PrintImageRequest request) {
        try {
            JSONObject options = new JSONObject();
            options.put("content", request.getContent());
            options.put("mode", 0); // 默认模式
            options.put("interval", request.getInterval());
            handler.post(() -> printModule.print(options));
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("打印失败: " + e.getMessage());
        }
    }

    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @PostMapping("/printBarcode")
    public BaseResponse printBarcode(@RequestBody PrintBarcodeRequest request) {
        try {
            JSONObject options = new JSONObject();
            options.put("content", request.getContent());
            options.put("barcodeType", request.getBarcodeType());
            handler.post(() -> printModule.printBarcode(options));
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("打印条形码失败: " + e.getMessage());
        }
    }


    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @GetMapping("/getVersion")
    public BaseResponse getVersion() {
        try {
            CountDownLatch latch = new CountDownLatch(1);
            AtomicReference<JSONObject> object1 = new AtomicReference<>(new JSONObject());

            handler.post(() -> {
                object1.set(printModule.getVersion());
                latch.countDown();
            });

            latch.await(2, TimeUnit.SECONDS);

            return BaseResponse.success(object1.get().get("version"));
        } catch (Exception e) {
            return BaseResponse.error("获取版本失败: " + e.getMessage());
        }
    }


    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @GetMapping("/getFontVersion")
    public BaseResponse getFontVersion() {
        try {
            CountDownLatch latch = new CountDownLatch(1);
            AtomicReference<JSONObject> object1 = new AtomicReference<>(new JSONObject());

            handler.post(() -> {
                object1.set(printModule.getFontVersion());
                latch.countDown();
            });

            latch.await(2, TimeUnit.SECONDS);

            return BaseResponse.success(object1.get().get("fontVersion"));
        } catch (Exception e) {
            return BaseResponse.error("获取字体版本失败: " + e.getMessage());
        }
    }


    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @GetMapping("/getBaudRate")
    public BaseResponse getBaudRate() {
        try {
            CountDownLatch latch = new CountDownLatch(1);
            AtomicReference<JSONObject> object1 = new AtomicReference<>(new JSONObject());

            handler.post(() -> {
                object1.set(printModule.getBaudRate());
                latch.countDown();
            });

            latch.await(2, TimeUnit.SECONDS);

            return BaseResponse.success(object1.get().get("baudRate"));
        } catch (Exception e) {
            return BaseResponse.error("获取波特率失败: " + e.getMessage());
        }
    }

    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @PostMapping("/setPrintSpeed")
    public BaseResponse setPrintSpeed(@RequestParam("speed") int speed) {
        try {
            handler.post(() -> printModule.setPrintSpeed(speed));
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("设置打印速度失败: " + e.getMessage());
        }
    }


    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @PostMapping("/setPrintChromaLevel")
    public BaseResponse setPrintChromaLevel(@RequestParam("chroma") int chroma) {
        try {
            handler.post(() -> printModule.setPrintChromaLevel(chroma));
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("设置打印浓度失败: " + e.getMessage());
        }
    }

    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @PostMapping("/setPrintAlignmentMode")
    public BaseResponse setPrintAlignmentMode(@RequestParam("mode") int mode) {
        try {
            handler.post(() -> printModule.setPrintAlignmentMode(mode));
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("设置打印对齐模式失败: " + e.getMessage());
        }
    }

    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @PostMapping("/setPrintRowSpacing")
    public BaseResponse setPrintRowSpacing(@RequestParam("spacing") int spacing) {
        try {
            handler.post(() -> printModule.setPrintRowSpacing(spacing));
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("设置行距失败: " + e.getMessage());
        }
    }

    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @PostMapping("/setPrintLeftMargin")
    public BaseResponse setPrintLeftMargin(@RequestParam("nl") int nl, @RequestParam("nh") int nh) {
        try {
            handler.post(() -> printModule.setPrintLeftMargin(nl, nh));
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("设置左边距失败: " + e.getMessage());
        }
    }

    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @PostMapping("/setFeedRow")
    public BaseResponse setFeedRow(@RequestParam("type") int type, @RequestParam("n") int n) {
        try {
            handler.post(() -> printModule.setFeedRow(type, n));
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("设置走纸行数失败: " + e.getMessage());
        }
    }

    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @PostMapping("/setGSPMode")
    public BaseResponse setGSPMode(@RequestParam("x") int x, @RequestParam("y") int y) {
        try {
            handler.post(() -> printModule.setGSPMode(x, y));
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("设置GSP模式失败: " + e.getMessage());
        }
    }

    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @GetMapping("/restoreDefault")
    public BaseResponse restoreDefault() {
        try {
            handler.post(printModule::restoreDefault);
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("恢复默认设置失败: " + e.getMessage());
        }
    }

    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @PostMapping("/setBarcodeHeight")
    public BaseResponse setBarcodeHeight(@RequestParam("height") int height) {
        try {
            handler.post(() -> printModule.setBarcodeHeight(height));
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("设置条码高度失败: " + e.getMessage());
        }
    }

    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @PostMapping("/setBarcodeWidth")
    public BaseResponse setBarcodeWidth(@RequestParam("width") int width) {
        try {
            handler.post(() -> printModule.setBarcodeWidth(width));
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("设置条码宽度失败: " + e.getMessage());
        }
    }

    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @PostMapping("/setBarcodeHRI")
    public BaseResponse setBarcodeHRI(@RequestParam("position") int position) {
        try {
            handler.post(() -> printModule.setBarcodeHRI(position));
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("设置条码HRI位置失败: " + e.getMessage());
        }
    }

    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @PostMapping("/setUnderlineMode")
    public BaseResponse setUnderlineMode(@RequestParam("n") int n) {
        try {
            handler.post(() -> printModule.setUnderlineMode(n));
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("设置下划线模式失败: " + e.getMessage());
        }
    }

    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @PostMapping("/setBoldMode")
    public BaseResponse setBoldMode(@RequestParam("n") int n) {
        try {
            handler.post(() -> printModule.setBoldMode(n));
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("设置粗体模式失败: " + e.getMessage());
        }
    }

    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @PostMapping("/setFontDimension")
    public BaseResponse setFontDimension(@RequestParam("n") int n) {
        try {
            handler.post(() -> printModule.setFontDimension(n));
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("设置字体尺寸失败: " + e.getMessage());
        }
    }


    @CrossOrigin(methods = {RequestMethod.POST, RequestMethod.GET})
    @PostMapping("/restoreFactory")
    public BaseResponse restoreFactory(@RequestParam("n") int n) {
        try {
            handler.post(() -> printModule.Restore_factory(n));
            return BaseResponse.success();
        } catch (Exception e) {
            return BaseResponse.error("恢复出厂设置失败: " + e.getMessage());
        }
    }
} 